<template>
  <div class="tool-item flex flex-col rounded-lg overflow-hidden tool-dom"
    :data-handle="toolsData.handle"
    :data-advertisement_id="toolsData.advertisement_id ? toolsData.advertisement_id : ''"
    data-position="Alternative"
    :data-index="toolPosIndex"
    :class="{'history-recommended': hasRealVal(toolsData.is_noticeable) && toolsData.is_noticeable === 1}">
    <a :href="toolsData.website"
      @click="handleExp(0, toolsData)"
      rel="dofollow"
      v-if="(hasRealVal(toolsData.is_recommend_now) && toolsData.is_recommend_now) || hasRealVal(toolsData.advertisement_id)"
      target="_blank"
      class="flex-shrink-0 px-8 pt-9 tool-linear go-tool-detail-pic">
      <div class="flex tool-pic items-end justify-center skeleton-bg"
        ref="imgBox">
        <common-image class="w-full h-full flex-shrink-0"
          :src="toolsData.image"
          :alt="toolName"></common-image>
      </div>
    </a>
    <common-link path="/tool/:handle"
      @click.native="handleExp(0, toolsData)"
      v-else
      target="_blank"
      :params="{ handle: toolsData.handle}"
      class="flex-shrink-0 px-8 pt-9 tool-linear go-tool-detail-pic">
      <div class="flex tool-pic items-end justify-center skeleton-bg"
        ref="imgBox">
        <common-image class="w-full h-full flex-shrink-0"
          :src="toolsData.image"
          :alt="toolName"></common-image>
      </div>
    </common-link>
    <div class="flex-1 bg-white px-6 pt-6 pb-4 flex flex-col justify-between">
      <div class="flex-1">
        <div class="block">
          <div class="flex items-center justify-between">
            <div class="block flex-1 w-0 fs0">
              <div class="relative fs0 inline-block max-w-full">
                <a :href="toolsData.website"
                  @click="handleExp(1, toolsData)"
                  rel="dofollow"
                  v-if="(hasRealVal(toolsData.is_recommend_now) && toolsData.is_recommend_now) || hasRealVal(toolsData.advertisement_id)"
                  target="_blank"
                  class="max-w-full inline-block go-tool-detail-name">
                  <div class="text-2xl font-semibold text-gray-1000 flex-1 truncate break-words hover:text-purple-1300"
                    :title="toolName">
                    {{ toolName }}
                  </div>
                </a>
                <common-link path="/tool/:handle"
                  v-else
                  @click.native="handleExp(1, toolsData)"
                  target="_blank"
                  :params="{ handle: toolsData.handle}"
                  class="max-w-full inline-block go-tool-detail-name">
                  <div class="text-2xl font-semibold text-gray-1000 flex-1 truncate break-words hover:text-purple-1300"
                    :title="toolName">
                    {{ toolName }}
                  </div>
                </common-link>
                <!-- <common-link path="/tool/:handle"
                  target="_blank"
                  :params="{ handle: toolsData.handle}">
                  <svg-icon className="absolute right-0 f-middle text-base flex-shrink-0 hover:text-purple-1300"
                    iconName='openTool'></svg-icon>
                </common-link> -->
              </div>
            </div>
            <div class="flex items-center flex-shrink-0 ml-3 pt-1 group text-gray-1300 cursor-pointer hover:text-purple-1300 group to-add-or-cancle-favorites"
              :class="{'text-purple-1300': toolsData.user_collected}"
              @click="addOrCancleFavorites()">
              <svg-icon className="text-xl -mt-1"
                iconName='star_filled'
                v-if="!loading"></svg-icon>
              <img :src="loadingSrc"
                class="loading h-5 w-5"
                alt=""
                srcset=""
                v-if="loading">
              <span class="ml-2 text-base text-gray-1000 group-hover:text-purple-1300">{{toolsData.collected_count | vReset}}</span>
            </div>
          </div>
          <a :href="toolsData.website"
            @click="handleExp(2, toolsData, true)"
            rel="dofollow"
            v-if="(hasRealVal(toolsData.is_recommend_now) && toolsData.is_recommend_now) || hasRealVal(toolsData.advertisement_id)"
            target="_blank"
            class="mt-3 text-base text-gray-1500 break-words tool-desc leading-7 go-tool-detail-description"
            :title="toolsData.description">
            {{toolsData.description}}
          </a>
          <common-link path="/tool/:handle"
            v-else
            @click.native="handleExp(2, toolsData, true)"
            target="_blank"
            :params="{ handle: toolsData.handle}"
            class="mt-3 text-base text-gray-1500 break-words tool-desc leading-7 go-tool-detail-description"
            :title="toolsData.description">
            {{toolsData.description}}
          </common-link>
        </div>
      </div>
      <div class="flex items-start flex-wrap flex-shrink-0 mt-5 gap-x-3 gap-y-3 maxHeight">
        <template v-for="(tItem, tKey) in toolsData.attributes">
          <div class="text-sm text-gray-1800 bg-gray-2100 max-w-max truncate rounded-2xl t-label"
            v-for="(cItem, cKey) in tItem.options"
            :key="`${tItem.handle}-${cItem.handle}-${tKey}-${cKey}`">
            {{cItem.name}}
          </div>
        </template>
        <common-link path="/category/:handle"
          :params='{handle:tItem.handle }'
          class="text-sm text-gray-1800 bg-gray-2100 max-w-max truncate rounded-2xl t-label hover:bg-purple-1300 hover:text-white go-category-link"
          v-for="(tItem, tKey) in toolsData.categories"
          :key="tKey">{{tItem.name}}</common-link>
      </div>
      <div class="flex-shrink-0 flex items-stretch justify-between mt-6">
        <a :href="toolsData.website"
          @click="handleExp(3, toolsData, true)"
          :rel="hasRealVal(toolsData.is_noticeable) && toolsData.is_noticeable === 1 ? 'dofollow' : 'nofollow'"
          target="_blank"
          class="flex-1 flex items-center justify-center h-38 text-base text-blue-1300 border border-blue-1300 duration-100 hover:bg-blue-1700 focus:bg-blue-1700 px-2 radius-19 view-btn">
          {{$t('view')}}
        </a>
        <div class="flex-shrink-0 flex items-center justify-center ml-4">
          <div class="flex-shrink-0 flex items-center"
            :title="$t('monthlyVisits')">
            <svg-icon className="text-sm mt--3"
              iconName='similarweb'></svg-icon>
            <span class="ml-2 text-sm text-gray-1000">{{toolsData.month_visited_count | vResetVisit}}</span>
          </div>

          <div class="flex-shrink-0 flex items-center flag ml-2"
            v-if="toolsData.traffic && (toolsData.traffic.top_region || toolsData.traffic.top_region_value)"
            :title="getTitle()">
            <img :src="getImage(toolsData.traffic.top_region)"
              alt=""
              srcset=""
              v-if="toolsData.traffic.top_region">
            <span class="text-sm text-gray-1000 ml-1"
              v-if="toolsData.traffic.top_region_value">{{(toolsData.traffic.top_region_value * 100).toFixed(2)}}%</span>
          </div>
        </div>
      </div>
      <div class="flex-shrink-0 flex items-stretch progress-country">
        <template v-if="toolsData.traffic && toolsData.traffic.top_traffic_sources && toolsData.traffic.top_traffic_sources.length > 0">
          <div class="flex-shrink-0 progress-item"
            v-for="(item,key) in toolsData.traffic.top_traffic_sources">
            <div class="country text-gray-1000">{{$t(item.title)}} ({{(item.value * 100).toFixed(2)}}%)</div>
          </div>
        </template>
      </div>
      <div class="flex-shrink-0 flex items-stretch progress">
        <template v-if="toolsData.traffic && toolsData.traffic.top_traffic_sources && toolsData.traffic.top_traffic_sources.length > 0">
          <div class="flex-shrink-0 progress-item"
            :style="getWidth(item)"
            v-for="(item,key) in toolsData.traffic.top_traffic_sources">
            <div class="progress-item-bar"></div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapActions, mapState } from 'vuex'
export default {
  name: 'Tools',
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      countries: (state) => state.countries,
    }),
    toolName() {
      return this.$websiteName(this.toolsData)
    },
  },
  props: {
    toolsData: {
      type: Object,
      default: {},
    },
    isExposure: {
      type: Boolean,
      default: false,
    },
    toolPosIndex: {
      type: Number,
      default: 1,
    },
  },
  mixins: [mixinsExposure],
  data() {
    return {
      loading: false,
      loadingSrc: require('@/static/images/loading.png'),
    }
  },
  //TODO
  watch: {
    toolsData: {
      handler() {
        if (this.toolsData && this.toolsData.image) {
          let iSrc = this.toolsData.image
          if (iSrc.indexOf('x-oss-process') === -1) {
            iSrc = `${iSrc}${
              iSrc.indexOf('?') === -1 ? '?' : '&'
            }x-oss-process=image/resize,l_600,m_lfit`
          }
          if (
            iSrc.indexOf('https://nav-station.oss-accelerate.aliyuncs.com') >= 0
          ) {
            iSrc = iSrc.replace(
              'https://nav-station.oss-accelerate.aliyuncs.com',
              'https://cdn-images.toolify.ai'
            )
          }
          this.toolsData.image = iSrc
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val ? val : 0
      }
    },
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
  },
  methods: {
    ...mapActions(['exposure']),
    resetPath(tHandle, cHandle) {
      let query = {}
      query.attributes = `${tHandle}-${cHandle}`
      return query
    },
    async addOrCancleFavorites() {
      this.loading = true
      try {
        try {
          let res

          switch (this.toolsData.user_collected) {
            case 0:
              res = await this.$axiosApi.postFavorites({
                handle: this.toolsData.handle,
              })
              break
            case 1:
              res = await this.$axiosApi.deleteFavorites({
                handle: this.toolsData.handle,
              })
              break
            default:
              console.log('error')
          }

          this.loading = false
          if (res && res.code === 200) {
            this.$message.success(
              this.toolsData.user_collected
                ? this.$i18n.t('cancelFavoritesSuccess')
                : this.$i18n.t('addFavoritesSuccess')
            )
            this.toolsData.collected_count = this.toolsData.user_collected
              ? parseInt(this.toolsData.collected_count) - 1
              : parseInt(this.toolsData.collected_count) + 1
            this.toolsData.user_collected = this.toolsData.user_collected
              ? 0
              : 1

            this.$emit('updateData', this.toolsData.handle)
          }
        } catch (error) {
          this.loading = false
          console.log(error)
        }
      } catch (error) {}
    },
    //判断是否有国旗
    getImage(name) {
      try {
        const image = require('@/static/images/flags/' + name + '.png')
        if (image) {
          return image
        } else {
          return ''
        }
      } catch (error) {
        //console.log(error)
      }
    },
    getWidth(item) {
      let total = this.toolsData.traffic.top_traffic_sources.reduce(
        (total, titem) => {
          return total + titem.value
        },
        0
      )
      return {
        width: `${((item.value / total) * 100).toFixed(2)}%`,
      }
    },
    getTitle() {
      let targetCountry = this.countries.find((item) => {
        return item.value === this.toolsData.traffic.top_region
      })
      let percent = `${(this.toolsData.traffic.top_region_value * 100).toFixed(
        2
      )}%`

      return `${
        targetCountry && targetCountry.label
          ? targetCountry.label
          : this.toolsData.traffic.top_region
      }: ${percent}`
    },
    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },

    handleExp(key = 0, toolsData, isOpensiteBtn = false) {
      this.getThrottledClickFunction(toolsData, key, (isOpensiteBtn = false))()
    },
    getThrottledClickFunction(toolsData, key, isOpensiteBtn = false) {
      let functionKey = `${toolsData.handle}-${key}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          if (this.isExposure) {
            let exporeData = this.getExporeData(
              toolsData,
              isOpensiteBtn ? 'Alternative OpenSite Btn' : 'Alternative',
              this.toolPosIndex,
              false
            )
            this.exposure({
              ...exporeData,
            })
          }
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
  },
}
</script>
<style lang='scss' scoped>
.tool-item {
  box-shadow: rgb(14 30 62 / 8%) 0px 3px 6px;
  &.history-recommended {
    border: 2px solid rgba(169, 176, 255, 1);
  }
  &:hover {
    box-shadow: rgb(14 30 62 / 12%) 0px 18px 34px;
  }

  .tool-desc {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
  }

  .tool-linear {
    background: linear-gradient(360deg, #eaeaff 0%, #c2c2ff 100%);
    .tool-pic {
      height: 186px;
      border-radius: 10px 10px 0px 0px;
      overflow: hidden;
    }
  }

  .tool-pic {
    img {
      border-radius: 10px 10px 0 0;
    }
  }

  .t-label {
    padding: 3px 10px;
  }

  .view-btn {
    max-width: 139px;
  }

  .flag {
    margin-top: -1px;
    img {
      width: 19px;
      height: 13px;
    }
  }

  .progress-country {
    width: 100%;
    overflow: hidden;
    margin-top: 12px;
    justify-content: space-between;
    min-height: 14px;
    .progress-item {
      .country {
        font-size: 12px;
        line-height: 14px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .maxHeight {
    max-height: 64px;
  }
  .progress {
    width: 100%;
    overflow: hidden;
    margin-top: 12px;
    min-height: 6px;
    //background: #f0f2f4;
    border-radius: 3px;
    .progress-item {
      .progress-item-bar {
        height: 6px;
        background: #195afe;
      }
      &:first-child {
        .progress-item-bar {
          border-radius: 3px 0 0 3px;
        }
      }
      &:last-child {
        .progress-item-bar {
          border-radius: 0 3px 3px 0;
        }
      }
      &:nth-child(1) {
        .progress-item-bar {
          background: #195afe;
        }
      }
      &:nth-child(2) {
        .progress-item-bar {
          background: #1dcdf5;
        }
      }
      &:nth-child(3) {
        .progress-item-bar {
          background: #fc3771;
        }
      }
    }
  }
}
</style>
